/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.github.florent37.camerafragment.internal.utils;

import ohos.aafwk.ability.fraction.FractionAbility;
import ohos.agp.window.service.DisplayManager;
import ohos.app.Context;
import ohos.global.configuration.Configuration;
import ohos.global.resource.NotExistException;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.image.common.PixelFormat;
import ohos.media.image.common.Rect;
import ohos.media.image.common.Size;

import java.io.IOException;
import java.io.InputStream;
import java.util.regex.Pattern;

/**
 * Utils 工具类
 *
 * @since 2021-05-25
 */
public class Utils {
    private static final int CONSTANT_2 = 2;
    private static final int CONSTANT_3 = 3;
    private static final String TAG = "Utils";

    private Utils() {
    }

    /**
     * 获取设备默认方向
     *
     * @param context 上下文
     * @return int整数
     */
    public static int getDeviceDefaultOrientation(FractionAbility context) {
        DisplayManager displayManager = DisplayManager.getInstance();
        Configuration config = context.getResourceManager().getConfiguration();
        int rotation = displayManager.getDefaultDisplay(context).get().getRotation();
        if ((rotation == 0 || rotation == CONSTANT_2) && config.direction == Configuration.DIRECTION_HORIZONTAL) {
            return Configuration.DIRECTION_HORIZONTAL;
        } else if ((rotation == 1 || rotation == CONSTANT_3) && config.direction == Configuration.DIRECTION_VERTICAL) {
            return Configuration.DIRECTION_HORIZONTAL;
        } else {
            return Configuration.DIRECTION_VERTICAL;
        }
    }

    /**
     * 得到Mime类型
     *
     * @param url 地址
     * @return String类型名字符
     */
    public static String getMimeType(String url) {
        String type = "";
        String extension = getFileExtensionFromUrl(url);
        if (!"".equals(extension)) {
            type = "image/jpg";
        } else {
            String reCheckExtension = getFileExtensionFromUrl(url.replaceAll("\\s+", ""));
            if (!"".equals(reCheckExtension)) {
                type = "image/jpg";
            }
        }
        return type;
    }

    /**
     * 从Url获取文件扩展名
     *
     * @param url 文件地址
     * @return String地址字符串
     */
    public static String getFileExtensionFromUrl(String url) {
        if (!"".equals(url)) {
            String url1 = url;
            int fragment = url1.lastIndexOf('#');
            if (fragment > 0) {
                url1 = url1.substring(0, fragment);
            }

            int query = url1.lastIndexOf('?');
            if (query > 0) {
                url1 = url1.substring(0, query);
            }

            int filenamePos = url1.lastIndexOf('/');
            String filename =
                0 <= filenamePos ? url1.substring(filenamePos + 1) : url1;

            // if the filename contains special characters, we don't
            // consider it valid for our matching purposes:
            if (!filename.isEmpty()
                && Pattern.matches("[a-zA-Z_0-9\\.\\-\\(\\)\\%]+", filename)) {
                int dotPos = filename.lastIndexOf('.');
                if (0 <= dotPos) {
                    return filename.substring(dotPos + 1);
                }
            }
        }

        return "";
    }

    /**
     * 通过资源ID获取位图对象
     *
     * @param context 上下文
     * @param resId 本地资源图片Id
     * @return PixelMap图片
     */
    public static PixelMap getPixelMap(Context context, int resId) {
        InputStream drawableInputStream = null;
        try {
            drawableInputStream = context.getResourceManager().getResource(resId);
            ImageSource.SourceOptions sourceOptions = new ImageSource.SourceOptions();
            sourceOptions.formatHint = "image/png";
            ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
            decodingOptions.desiredSize = new Size(0, 0);
            decodingOptions.desiredRegion = new Rect(0, 0, 0, 0);
            decodingOptions.desiredPixelFormat = PixelFormat.ARGB_8888;
            ImageSource imageSource = ImageSource.create(drawableInputStream, null);
            PixelMap pixelMap = imageSource.createPixelmap(decodingOptions);
            return pixelMap;
        } catch (IOException err) {
            Log.error(TAG, "getPixelMap IOException " + err.getLocalizedMessage());
        } catch (NotExistException error) {
            Log.error(TAG, "getPixelMap NotExistException " + error.getLocalizedMessage());
        } finally {
            try {
                if (drawableInputStream != null) {
                    drawableInputStream.close();
                }
            } catch (IOException er) {
                Log.error(TAG, " getPixelMap finally IOException " + er.getLocalizedMessage());
            }
        }
        ImageSource imageSource = ImageSource.create(drawableInputStream, null);
        ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
        PixelMap pixelMap = imageSource.createPixelmap(decodingOptions);
        return pixelMap;
    }
}
